﻿using System;
using System.Threading.Tasks;
using System.Linq;
using Easy.Cloud.Communication.Sms.Core;
using Easy.Cloud.Communication.Sms.Tencent.Options;
using System.Net.Mail;
using System.Net;
using System.Runtime;
using Easy.Shared.Exception;
using TencentCloud.Sms.V20210111;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20210111.Models;

namespace Easy.Cloud.Communication.Sms.Tencent
{
    public class TencentSmsClient : ISmsClient
    {
        private readonly TencentOptions _option;

        public TencentSmsClient(TencentOptions option)
        {
            _option = option;
        }

        public async Task<ResponseMessage> SendAsync(SendRequest request)
        {
            try
            {
                var client = await CreateClient();

                var sendSmsRequest = await CreateSendSmsRequest(request);

                SendSmsResponse resp = client.SendSmsSync(sendSmsRequest);

                var status = resp.SendStatusSet.First();

                if (status.Code.Equals("Ok"))
                    return new ResponseMessage(true, resp);

                return new ResponseMessage(false, resp);
            }
            catch (Exception e)
            {
                throw new TencentException(e.ConvertString());
            }
        }


        private Task<SmsClient> CreateClient()
        {
            var cred = new Credential()
            {
                SecretId = _option.SecretId,
                SecretKey = _option.SecretKey
            };

            ClientProfile clientProfile = new ClientProfile();

            clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;

            HttpProfile httpProfile = new HttpProfile();

            httpProfile.ReqMethod = "POST";

            httpProfile.Endpoint = _option.Endpoint;

            clientProfile.HttpProfile = httpProfile;

            SmsClient client = new SmsClient(cred, _option.Region, clientProfile);

            return Task.FromResult(client);
        }


        private Task<SendSmsRequest> CreateSendSmsRequest(SendRequest request)
        {
            var phoneNumberArray = request.PhoneNumbers.Split(',');

            var template = _option.TemplateItem.Single(s => s.Name.Equals(request.Template));

            var signName = _option.SignNameItem.Single(s => s.Name.Equals(request.SignName));

            var templateParamArray = request.TemplateParam.Split(',');

            SendSmsRequest req = new SendSmsRequest();

            req.SmsSdkAppId = _option.SmsSdkAppId;

            req.SignName = signName.ToString();

            req.TemplateId = template.Value;

            req.TemplateParamSet = templateParamArray;

            req.PhoneNumberSet = phoneNumberArray;

            return Task.FromResult(req);
        }
    }
}